function ListNode(val, next) {
  if (Array.isArray(val)) {
    // 给定一个数组，创建一个头结点
    this.val = val[0];
    let cur = this;
    for (let i = 1; i < val.length; i++) {
      cur.next = new ListNode(val[i]);
      cur = cur.next;
    }
  } else {
    this.val = val === undefined ? 0 : val;
    this.next = next === undefined ? null : next;
  }
}
ListNode.prototype.toString = function () {
  let cur = this;
  let res = '';
  while (cur) {
    res += `${cur.val} --> `;
    cur = cur.next;
  }
  return res;
};

/**
 * @param {ListNode} head
 * @param {number} val
 * @return {ListNode}
 */
// 使用虚拟头结点解决这个问题
// 删除一个元素，其实就是找到待删除元素的前一个节点，然后进行改变next的指向，从而删除元素
var removeElements = function (head, val) {
  //
  var dummyNode = new ListNode(null, head);
  let prev = dummyNode;
  while (prev.next) {
    if (prev.next.val === val) {
      prev.next = prev.next.next;
    } else {
      prev = prev.next;
    }
  }
  // 返回头结点
  return dummyNode.next;
};

// 不使用虚拟头节点删除元素
var removeElements = function (head, val) {
  // 删除头节点元素
  while (head && head.val === val) {
    head = head.next;
  }
  if (!head) {
    return null;
  }

  let prev = head;
  while (prev.next) {
    if (prev.next.val === val) {
      prev.next = prev.next.next;
    } else {
      prev = prev.next;
    }
  }
  return head;
};

var head = new ListNode([1, 2, 3, 4, 4, 3, 5]);
head = removeElements(head, 3);
console.log(head.toString());
